package com.li.network.lab_4;

import java.util.Map;

public class HttpResponse {
    private String version;
    private String code;
    private String description;
    private Map<String, String> headers;
    private String body;

    public void setVersion(String version) {
        this.version = version;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getVersion() {
        return version;
    }

    public String getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public String getBody() {
        return body;
    }

    @Override
    public String toString() {
        return "HttpResponse{" +
                "version='" + version + '\'' +
                ", code='" + code + '\'' +
                ", description='" + description + '\'' +
                ", headers=" + headers +
                ", body='" + body + '\'' +
                '}';
    }

    public byte[] getBytes() {
        String next = "\r\n";
        //状态行
        String stateLine = version + " " + code + " " + description + next;
        //消息头
        StringBuilder headerLine = new StringBuilder();
        headers.forEach((k, v) -> {
            headerLine.append(k + ":" + v).append(next);
        });
        //消息体
        String bodyLine = null;
        if (body != null) {
            bodyLine = next + body;
        }
        byte[] result;
        byte[] stateBytes = stateLine.getBytes();
        byte[] headerBytes = headerLine.toString().getBytes();
        if (bodyLine != null) {
            byte[] bodyBytes = bodyLine.getBytes();
            result = new byte[stateBytes.length + headerBytes.length + bodyBytes.length];
            System.arraycopy(stateBytes, 0, result, 0, stateBytes.length);
            System.arraycopy(headerBytes, 0, result, 0, headerBytes.length);
            System.arraycopy(bodyBytes, 0, result, 0, bodyBytes.length);
        } else {
            result = new byte[stateBytes.length + headerBytes.length];
            System.arraycopy(stateBytes, 0, result, 0, stateBytes.length);
            System.arraycopy(headerBytes, 0, result, 0, headerBytes.length);
        }
        return result;
    }
}
